import requests
import json
import getpass


class Webapi():
    def __init__(self, username, password):
        self.username = username
        self.password = password
        self.loginurl = loginurl
        self.sshkeyUrl = sshkeyUrl
        self.headers = {
            "Content-Type": "application/x-www-form-urlencoded",
            "Authorization": "Token " + self.get_token()
        }

    def get_token(self):
        """
        获取token
        """
        Data = {
            "username": self.username,
            "password": self.password
        }
        res = requests.post(self.loginurl, Data)
        token = res.json()['data']['token']
        return token

    def getManageKey(self):

        try:
            response = requests.get(
                self.sshkeyUrl, headers=self.headers)
            # resone = self._formatResponseOne(response)
            res = response.json()['data']
            return res[0]
        except Exception as e:
            error_msg = 'Get Manage Key Failed ：{}'.format(str(e))
            raise ValueError(error_msg)


if __name__ == '__main__':
    loginurl = "http://10.88.0.157/api/oauth/login"
    sshkeyUrl = "http://10.88.0.157/api/cmdb/sshkey"

    username = "OperatorCmdb"
    passwd = getpass.getpass()

    req = Webapi(username, passwd)
    # print(req.headers)
    print(req.getManageKey())
